package com.wuhuacloud.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.wuhuacloud.common.constant.Constants;
import com.wuhuacloud.common.core.controller.BaseController;
import com.wuhuacloud.common.core.domain.AjaxResult;
import com.wuhuacloud.common.core.domain.entity.SysDictData;
import com.wuhuacloud.common.core.domain.entity.SysUser;
import com.wuhuacloud.common.core.page.TableDataInfo;
import com.wuhuacloud.common.utils.DateUtils;
import com.wuhuacloud.common.utils.SecurityUtils;
import com.wuhuacloud.common.utils.StringUtils;
import com.wuhuacloud.common.utils.ip.IpUtils;
import com.wuhuacloud.fb.domain.*;
import com.wuhuacloud.fb.service.*;
import com.wuhuacloud.framework.web.service.SysLoginService;
import com.wuhuacloud.system.domain.SysFileInfo;
import com.wuhuacloud.system.domain.SysNotice;
import com.wuhuacloud.system.service.ISysDictTypeService;
import com.wuhuacloud.system.service.ISysFileInfoService;
import com.wuhuacloud.system.service.ISysNoticeService;
import com.wuhuacloud.system.service.ISysUserService;
import com.wuhuacloud.system.service.cloud.OSSFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 接口类
 */
@RestController
@RequestMapping("/api")
public class ApiController extends BaseController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ICanteenService canteenService;

    @Autowired
    private ICanteenTimeService canteenTimeService;

    @Autowired
    private IWalletService walletService;

    @Autowired
    private ISuggestService suggestService;

    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private ITradeInfoService tradeInfoService;

    @Autowired
    private ISysFileInfoService sysFileInfoService;

    private static final Logger log = LoggerFactory.getLogger(ApiController.class);
    /**
     * 登录接口
     * @param username
     * @param password
     * @param dataType
     * @param ecafeNotRedirect
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public AjaxResult mobileLogin(String username, String password, String dataType, String ecafeNotRedirect)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(username, password);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 获取当前用户表
     * @return
     */
    @RequestMapping(value = "user", method = RequestMethod.GET)
    public AjaxResult getUserInfo()
    {
        return AjaxResult.success(SecurityUtils.getLoginUser().getUser());
    }


    /**
     * 修改密码
     */
    @PostMapping("/modifyPassword")
    public AjaxResult resetPwd(@RequestBody Map<String,String> data)
    {
        String oldpassword = data.get("oldpassword");
        String rePassword = data.get("rePassword");
        SysUser user = userService.selectUserById(SecurityUtils.getLoginUser().getUser().getUserId());
        if(SecurityUtils.matchesPassword(oldpassword,user.getPassword())){
            user.setPassword(SecurityUtils.encryptPassword(rePassword));
            user.setUpdateBy(SecurityUtils.getUsername());
            toAjax(userService.resetPwd(user));
        }else{
            return AjaxResult.error("请输入正确的旧密码！");
        }
        return AjaxResult.success();
    }

    /**
     * 获取食堂列表
     * @return
     */
    @RequestMapping(value = "canteen", method = RequestMethod.GET)
    public AjaxResult getCanteenList(){

        List<Map> ct =new ArrayList<Map>();

        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        List<Canteen> canteenList = canteenService.selectCanteenDept(deptId);
        for(Canteen canteen : canteenList){
            CanteenTime canteenTime = new CanteenTime();
            canteenTime.setCanteenId(canteen.getId());


            Map resultCanteenTime = new HashMap();
            List<CanteenTime> canteenTimeList = canteenTimeService.selectCanteenTimeList(canteenTime);
            for(CanteenTime cTime :canteenTimeList){
                Map d = new HashMap();
                d.put("startTime",cTime.getStartTime());
                d.put("stopTime",cTime.getStopTime());
                resultCanteenTime.put(cTime.getMealType(),d);
            }

            Map d =new HashMap();
                d.put("canteen",canteen);
                d.put("canteenTime",resultCanteenTime);
                ct.add(d);
        }





        return AjaxResult.success(ct);
    }

    /**
     * 获取食堂菜单
     * @return
     */
    @RequestMapping(value = "canteen/menu/{canteenId}/{date}/{mealType}", method = RequestMethod.GET)
    public AjaxResult getCanteenMenu(@PathVariable String date,@PathVariable Long canteenId,@PathVariable String mealType){

        CanteenMenu canteenMenu = new CanteenMenu();
        canteenMenu.setMealDate(date);
        canteenMenu.setCanteenId(canteenId);
        canteenMenu.setMealType(mealType);

        List<CanteenMenu> canteenMenuList = canteenService.selectCanteenMenuList(canteenMenu);

        return AjaxResult.success(canteenMenuList);
    }


    /**
     * 获取本周食堂菜单
     * @param canteenId
     * @return
     */
    @RequestMapping(value = "canteen/menu/{canteenId}", method = RequestMethod.GET)
    public AjaxResult getCurrentWeekCanteenMenu(@PathVariable Long canteenId){

        //星期数据
        String[] weekNameArr = new String[]{"mon","tues","wed","thur","fri","sat","sun"};

        //本周日期
        String[] currentWeek = DateUtils.getDateArr();

        //餐类型
        List<SysDictData> sysDictDataList =sysDictTypeService.selectDictDataByType("fb_meal_type");

        JSONObject resp = new JSONObject();

        for (int i=0;i<currentWeek.length;i++){
            JSONObject dataObj = new JSONObject();
            for (SysDictData sysDictData : sysDictDataList){
                String mealType =sysDictData.getDictValue();
                CanteenMenu canteenMenu = new CanteenMenu();
                canteenMenu.setMealDate(currentWeek[i]);
                canteenMenu.setCanteenId(canteenId);
                canteenMenu.setMealType(mealType);
                List<CanteenMenu> canteenMenuList = canteenService.selectCanteenMenuList(canteenMenu);
                dataObj.put(mealType,canteenMenuList);
            }
            dataObj.put("date",currentWeek[i]);
            resp.put(weekNameArr[i],dataObj);
        }

        return AjaxResult.success(resp);
    }


    /**
     * 获取当前用户的余额
     * @return
     */
    @RequestMapping(value = "wallet/balance", method = RequestMethod.GET)
    public AjaxResult getwallet(){

        BigDecimal balance = new BigDecimal(0);
        Wallet wallet = walletService.selectWalletById(SecurityUtils.getLoginUser().getUser().getUserId());
        if(StringUtils.isNotNull(wallet)){
            balance = wallet.getBalance();
        }

        return AjaxResult.success(balance);
    }


    /**
     * 获取食堂餐类型
     * @return
     */
    @RequestMapping(value = "canteen/{canteenId}/meal/type", method = RequestMethod.GET)
    public AjaxResult getCanteenMenu(@PathVariable String canteenId){
        List<SysDictData> sysDictDataList =sysDictTypeService.selectDictDataByType("fb_meal_type");
        return AjaxResult.success(sysDictDataList);
    }

    /**
     * 新增意见反馈
     * @param suggest
     * @return
     */
    @RequestMapping(value = "suggest", method = RequestMethod.POST)
    public AjaxResult add(@RequestBody Suggest suggest)
    {
        suggest.setCreateBy(SecurityUtils.getUsername());
        suggest.setCreateTime(DateUtils.getNowDate());
        return toAjax(suggestService.insertSuggest(suggest));
    }

    /**
     * 查询意见反馈
     * @return
     */
    @RequestMapping(value = "suggest", method = RequestMethod.GET)
    public TableDataInfo list(Suggest suggest)
    {
        startPage();
        suggest.setCreateBy(SecurityUtils.getUsername());
        List<Suggest> list = suggestService.selectSuggestList(suggest);
        return getDataTable(list);
    }

    /**
     * 获取意见详细信息
     */
    @RequestMapping(value = "suggest/{suggestId}", method = RequestMethod.GET)
    public AjaxResult getInfo(@PathVariable("suggestId") String suggestId)
    {
        return AjaxResult.success(suggestService.selectSuggestById(suggestId));
    }

    /**
     * 获取公告类型
     * @return
     */
    @RequestMapping(value = "notice/type", method = RequestMethod.GET)
    public AjaxResult getNoticeType(){
        List<SysDictData> sysDictDataList =sysDictTypeService.selectDictDataByType("sys_notice_type");
        return AjaxResult.success(sysDictDataList);
    }

    /**
     * 获取公告信息
     * @param notice
     * @return
     */
    @RequestMapping(value = "notice", method = RequestMethod.GET)
    public TableDataInfo list(SysNotice notice)
    {
        startPage();
        notice.setStatus("0");
        notice.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId().toString());
        List<SysNotice> list = noticeService.selectNoticeList(notice);
        return getDataTable(list);
    }

    /**
     * 查询当前用户消费记录
     * @return
     */
    @RequestMapping(value = "/canteen/trade", method = RequestMethod.GET)
    public TableDataInfo tradeList(@RequestParam("tradeTime") String tradeTime)
    {
        Map query = new HashMap();
        query.put("tradeTime",tradeTime);
        query.put("userId",SecurityUtils.getLoginUser().getUser().getUserId());
        List<TradeInfo> list = tradeInfoService.selectTradeInfoListDiy(query);
        return getDataTable(list);
    }

    /**
     * 根据当前用户和年月统计消费总额、充值等记录
     * @param tradeTime
     * @return
     */
    @RequestMapping(value = "/canteen/trade/all", method = RequestMethod.GET)
    public AjaxResult selectTradeInfoAll(@RequestParam("tradeTime") String tradeTime){
        Map query = new HashMap();
            query.put("tradeTime",tradeTime);
            query.put("userId",SecurityUtils.getLoginUser().getUser().getUserId());
        return AjaxResult.success(tradeInfoService.selectTradeInfoAll(query));
    }

    /**
     * 新增消费
     * @param tradeInfo
     * @return
     */
    @RequestMapping(value = "/canteen/trade", method = RequestMethod.POST)
    public AjaxResult addCanteenTrade(@RequestBody TradeInfo tradeInfo){

        try{
            Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
            //当前登录人
            String dqr = SecurityUtils.getUsername();
            Wallet wallet = walletService.selectWalletById(userId);
            if(StringUtils.isNull(wallet)){
                return AjaxResult.error("消费异常");
            }

            BigDecimal payment = new BigDecimal(tradeInfo.getPayment());

            if(wallet.getBalance().compareTo(payment) == -1){
                return AjaxResult.error("余额不足");
            }
            //更新用户余额表
            wallet.setBalance(wallet.getBalance().subtract(payment));
            wallet.setUpdateBy(dqr);
            walletService.updateWallet(wallet);
            //重置消费金额
            tradeInfo.setPayment("-"+tradeInfo.getPayment());
            //交易用户
            tradeInfo.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            //交易IP
            tradeInfo.setTradeIp(IpUtils.getHostIp());
            //
            tradeInfo.setCreateBy(SecurityUtils.getUsername());
            tradeInfoService.insertTradeInfo(tradeInfo);


        }catch (Exception e){
            e.printStackTrace();
            log.error("消费异常",e.getMessage());
            return AjaxResult.error("消费异常,请联系管理员!");
        }

        return AjaxResult.success();
    }

    /**
     * 通用删除
     */
    @PostMapping("/upload/del")
    public AjaxResult delFile(SysFileInfo sysFileInfo){

        OSSFactory.build().delFile(sysFileInfo.getFileName());

        sysFileInfoService.deleteSysFileInfoById(sysFileInfo.getFileId());

        return AjaxResult.success();
    }

}
